package com.zmn.oms.dubbo.impl.zmn.normal.order;

import org.apache.dubbo.config.annotation.Reference;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.common.utils.validator.ValidateResult;
import com.zmn.common.utils.validator.ValidatorUtil;
import com.zmn.dms.common.enums.DiscountTypeEnums;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.enums.EncryptFieldTypeEnum;
import com.zmn.oms.dubbo.dto.common.work.OrderDetailDiscountDRO;
import com.zmn.oms.dubbo.dto.zmn.order.*;
import com.zmn.oms.dubbo.dto.zmn.order.user.UserOrderPageDRO;
import com.zmn.oms.dubbo.dto.zmn.order.user.UserOrderQueryDIO;
import com.zmn.oms.dubbo.dto.zmn.serviceitem.OrderServiceItemDRO;
import com.zmn.oms.dubbo.impl.zmn.order.OrderBaseRemoteService;
import com.zmn.oms.dubbo.interfaces.zmn.normal.order.ZsNormalOrderRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.dto.order.zmn.ZsNormalNewOrderDTO;
import com.zmn.oms.model.dto.order.zmn.ZsNormalUpdateOrderDTO;
import com.zmn.oms.model.entity.comment.OrderComment;
import com.zmn.oms.model.entity.comment.OrderCommentDetail;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.entity.work.list.OrderWorkOuterQuery;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.oms.model.vo.work.modify.amount.ZsServiceItemVO;
import com.zmn.oms.services.interfaces.comment.OrderCommentService;
import com.zmn.oms.services.interfaces.orderencrypt.OrderEncryptService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.discount.ZsOrderDiscountBService;
import com.zmn.oms.zmn.normal.business.interfaces.order.ZsNormalOrderBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.ZsNormalWorkBService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.saas.dubbo.constant.SaasDubboConsts;
import com.zmn.saas.dubbo.dto.shop.ShopDIO;
import com.zmn.saas.dubbo.dto.shop.ShopDRO;
import com.zmn.saas.dubbo.interfaces.shop.ShopRemoteService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：订单 remote service
 *
 * @author liuying
 * @date 2018/11/07 15:10
 * @see ZsNormalOrderWorkRemoteServiceImpl
 */
@Deprecated
@Service(loadbalance = "roundrobin", timeout = 20000, retries = 2, version = DubboConsts.INTERFACE_VERSION, validation = "false")
public class ZsNormalOrderRemoteServiceImpl extends OrderBaseRemoteService implements ZsNormalOrderRemoteService {

    static final String TAG = "啄木鸟-普通单";
    @Autowired
    OrderWorkListBService orderWorkListBService;
    @Autowired
    OrderCommentService orderCommentService;
    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderProductService orderProductService;
    @Autowired
    OrderLogBService orderLogBService;
    @Autowired
    ZsNormalWorkBService zsNormalWorkBService;
    @Autowired
    ZsNormalOrderBService zsNormalOrderBService;
    @Autowired
    ZsOrderDiscountBService zsOrderDiscountBService;
    @Autowired
    OrderEncryptService orderEncryptService;

    @Reference(version = SaasDubboConsts.INTERFACE_VERSION, check = false)
    ShopRemoteService shopRemoteService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public com.zmn.common.dto2.ResponseDTO<OrderDRO> getOrderWorkByOuterId(@NotNull String outerId) {

        logger.info("#oms#通过第三方订单id查询 {}", outerId);

        OrderWorkOuterQuery query = new OrderWorkOuterQuery();
        query.setOuterId(outerId);
        List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);

        if (esOrderWorkList.isEmpty()) {
            return com.zmn.common.dto2.ResponseDTO.fail("订单不存在");
        }
        // 解密电话和地址
        orderEncryptService.batchDecryptEsOrderWork(esOrderWorkList,EncryptFieldTypeEnum.USER_TELPHONE,EncryptFieldTypeEnum.USER_ADDRESS);
        OrderDRO orderDRO = this.getOrderDRO(esOrderWorkList.get(0));
        return com.zmn.common.dto2.ResponseDTO.success(orderDRO);
    }

    @Override
    public ResponseDTO<Integer> getCouponDiscountAmountByOrderIdList(List<Long> orderIdList) {
        Integer couponDiscountAmount = orderWorkListBService.getCouponDiscountAmountByOrderIdList(orderIdList);
        return ResponseUtil.responseSuccess(couponDiscountAmount, DubboConsts.OK);
    }

    @Override
    public ResponseDTO<OrderDRO> getOrderByWarrantyCode(String warrantyCode) {
        try {
            OrderWorkQuery query = new OrderWorkQuery();
            query.setWarrantyCode(warrantyCode);
            List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);
            if (esOrderWorkList.isEmpty()) {
                return ResponseUtil.responseFail("订单不存在");
            }
            // 解密电话和地址
            orderEncryptService.batchDecryptEsOrderWork(esOrderWorkList, EncryptFieldTypeEnum.USER_TELPHONE, EncryptFieldTypeEnum.USER_ADDRESS);
            OrderDRO orderDRO = this.getOrderDRO(esOrderWorkList.get(0));
            return ResponseUtil.responseSuccess(orderDRO, DubboConsts.OK);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[{}] 获取订单错误：{}", TAG, e);
            return ResponseUtil.responseFail(e.getMessage());
        }
    }

    @Override
    public ResponseDTO<WeixinOrderDetailDRO> getWeixinOrderDetailById(Long orderId) {

        OrderWork dbOrderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderId, orderId);
        if (dbOrderWork == null) {
            return ResponseUtil.responseFail("not find order!");
        }

        WeixinOrderDetailDRO weixinOrderDetail = getWeixinOrderDetailDRO(dbOrderWork);
        logger.debug("订单详情DRO[{}]", weixinOrderDetail);
        return ResponseUtil.responseSuccessData(weixinOrderDetail);
    }

    @Override
    public ResponseDTO cancelOrder(CancelOrderDIO cancelOrderDIO) {
        logger.info("[{}] 取消订单：{}", TAG, cancelOrderDIO);

        ValidateResult validateResult = ValidatorUtil.validator(cancelOrderDIO);
        if (!validateResult.isSuccess()) {
            logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
            return ResponseUtil.responseFail("提交参数错误");
        }

        cancelOrderDIO.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_USER);
        return super.cancelOrder(cancelOrderDIO);
    }

    @Override
    public ResponseDTO<NewOrderDRO> updateOrder(UpdateOrderDIO updateOrderDIO) {
        logger.info("[{}] 修改订单：{}", TAG, updateOrderDIO);

        ValidateResult validateResult = ValidatorUtil.validator(updateOrderDIO);
        if (!validateResult.isSuccess()) {
            logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
            return ResponseUtil.responseFail("提交参数错误：" + validateResult.toString());
        }

        // DIO转换
        ZsNormalUpdateOrderDTO normalNewOrderDTO = BeanMapper.map(updateOrderDIO, ZsNormalUpdateOrderDTO.class);

        return super.updateOrder(normalNewOrderDTO);
    }

    @Override
    public ResponseDTO<Boolean> updateFinalPriceOrderToAfterPay(Long orderId) {
        logger.info("[{}] 修改为后付：{}", TAG, orderId);

        boolean flag = orderWorkBService.updateFinalPriceOrderToAfterPay(orderId);
        return ResponseUtil.responseSuccessData(flag);
    }

    @Override
    public ResponseDTO<NewOrderDRO> addOrder(NewOrderDIO newOrderDIO) {
        logger.info("[{}] 添加订单：{}", TAG, newOrderDIO);

        ValidateResult validateResult = ValidatorUtil.validator(newOrderDIO);
        if (!validateResult.isSuccess()) {
            logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
            return ResponseUtil.responseFail("提交参数错误：" + validateResult.toString());
        }
        if (StringUtils.isBlank(newOrderDIO.getOperator())) {
            newOrderDIO.setOperator("系统");
        }


        // DIO转换
        ZsNormalNewOrderDTO normalNewOrderDTO = BeanMapper.map(newOrderDIO, ZsNormalNewOrderDTO.class);
        normalNewOrderDTO.setReceiverManner(OrderConsts.RECEIVE_MANNER_MANUAL);
        normalNewOrderDTO.setAutoDistribute(newOrderDIO.getDutyMasterId());
        try {
            logger.info("未替换下单接口：[com.zmn.oms.dubbo.impl.zmn.normal.order.ZsNormalOrderRemoteServiceImpl.addOrder]，下单渠道：[{}]，下单方式：[{}]", normalNewOrderDTO.getChannelId(), normalNewOrderDTO.getReceiveEntranceId());
            return super.addOrder(normalNewOrderDTO);
        } catch (Exception e) {
            return ResponseUtil.responseFail(e.getMessage());
        }
    }

    @Override
    public ResponseDTO<SimpleOrderDRO> getMyOrderListByUserId(Long userId) {
        OrderWorkQuery query = new OrderWorkQuery();
        query.setUserId(userId);
        query.setPageSize(1000);
        query.setPageIndex(1);
        query.setOrderField("receiveTime");
        query.setWorkType(Lists.newArrayList(OrderConsts.ORDER_TYPE_REWORK, OrderConsts.ORDER_TYPE_NEW));
        List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(query);
        List<SimpleOrderDRO> orderDROList = Lists.newLinkedList();

        if (CollectionUtils.isEmpty(esOrderWorkList)) {
            return ResponseUtil.responseSuccessItems(orderDROList);
        }

        List<Long> orderIdList = esOrderWorkList.stream().map(EsOrderWork::getOrderId).collect(Collectors.toList());
        List<OrderWork> orderWorkList = orderWorkService.listEsOrderWorkByOrderIdList(orderIdList);
        Map<Long, OrderWork> orderWorkMap = orderWorkList.stream().collect(Collectors.toMap(OrderWork::getWorkId, e -> e));

        esOrderWorkList.forEach(item -> {
            SimpleOrderDRO simpleOrderDRO = this.getSimpleOrderDRO(item);
            OrderWork orderWork = orderWorkMap.get(item.getId());
            if (orderWork == null) {
                return;
            }
            simpleOrderDRO.setFinalPrice(orderWork.getFinalPrice());
            simpleOrderDRO.setReceiveTime(orderWork.getReceiveTime());
            simpleOrderDRO.setPrepayStatus(orderWork.getPrepayStatus());
            simpleOrderDRO.setRefundStatus(OrderConsts.getUserRefundStatus(NumberUtil.isNotNullOrZero(orderWork.getRefundTargetWorkId()),orderWork.getRefundReviewStatus(), orderWork.getPayStatus()));
            simpleOrderDRO.setOriginalAmount(orderWork.getOriginalAmount());
            simpleOrderDRO.setTotalAmount(this.getTotalAmount(orderWork));
            simpleOrderDRO.setFactAmount(this.factAmount(orderWork));
            orderDROList.add(simpleOrderDRO);
        });
        return ResponseUtil.responseSuccessItems(orderDROList);
    }

    @Override
    public com.zmn.common.dto2.ResponseDTO<UserOrderPageDRO> listPageOrderByUserId(UserOrderQueryDIO query) {

        ValidateResult validateResult = ValidatorUtil.validator(query);
        if (!validateResult.isSuccess()) {
            logger.error("listPageOrderByUserId 参数错误：{}", validateResult.toString());
            return com.zmn.common.dto2.ResponseDTO.fail(validateResult.getErrMsg()[0]);
        }

        OrderWorkQuery orderWorkQuery = new OrderWorkQuery();
        orderWorkQuery.setUserId(query.getUserId());
        orderWorkQuery.setPageSize(query.getPageSize());
        orderWorkQuery.setPageIndex(query.getPageIndex());
        orderWorkQuery.setOrderField("receiveTime");
        orderWorkQuery.setWorkType(Lists.newArrayList(OrderConsts.ORDER_TYPE_REWORK, OrderConsts.ORDER_TYPE_NEW));
        List<EsOrderWork> esOrderWorkList = orderWorkListBService.listPageOrderWorkByQuery(orderWorkQuery);

        List<SimpleOrderDRO> orderDROList = Lists.newLinkedList();
        UserOrderPageDRO pageDRO = new UserOrderPageDRO();
        pageDRO.setTotalCount(orderWorkQuery.getTotalCount());
        pageDRO.setOrderList(orderDROList);

        if (CollectionUtils.isEmpty(esOrderWorkList)) {
            return com.zmn.common.dto2.ResponseDTO.success(pageDRO);
        }

        esOrderWorkList.forEach(item -> {
            SimpleOrderDRO simpleOrderDRO = this.getSimpleOrderDRO(item);
            simpleOrderDRO.setFinalPrice(Objects.equals(true, item.getIsFinalPrice())
                    && Objects.equals(item.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE) ? GlobalConsts.YES : GlobalConsts.NO);
            simpleOrderDRO.setRefundStatus(OrderConsts.getUserRefundStatus(NumberUtil.isNotNullOrZero(item.getRefundTargetWorkId()),item.getRefundReviewStatus(), item.getPayStatus()));
            simpleOrderDRO.setReceiveTime(item.getReceiveTime());
            simpleOrderDRO.setPrepayStatus(item.getPrepayStatus());
            simpleOrderDRO.setOriginalAmount(item.getOriginalAmount());
            simpleOrderDRO.setTotalAmount(item.getTotalAmount());
            simpleOrderDRO.setFactAmount(this.factAmountFromEsOrder(item));
            simpleOrderDRO.setWorkStatusName(item.getStatusName());
            simpleOrderDRO.setWorkResultStatusName(item.getResultStatusName());
            orderDROList.add(simpleOrderDRO);
        });

        return com.zmn.common.dto2.ResponseDTO.success(pageDRO);
    }

    @Override
    public ResponseDTO<OrderCountDRO> getOrderCountByProductId(Integer productId, Date month) {
        if (productId == null) {
            return ResponseUtil.responseFail("提交参数错误：产品id不能为空。");
        }
        if (month == null) {
            // 如果没提供月份，默认查当月
            month = DateUtil.getNow();
        }
        String monthFirstDay = DateUtil.getMonthFirstDay(month);
        String monthLastDay = DateUtil.getMonthLastDay(month);

        OrderWorkQuery query = new OrderWorkQuery();
        query.setProductId(productId);
        query.setReceiveTime(monthFirstDay + "," + monthLastDay);
        // 只查微信渠道
        query.setChannelIdList(Lists.newArrayList(GlobalConsts.CHANNEL_WEIXIN_ID));
        Integer orderCount = orderWorkListBService.countOrderWorkByQuery(query);
        logger.debug("[{}]后端产品查询销量数据[{}]", query, orderCount);
        OrderCountDRO orderCountDRO = new OrderCountDRO();
        orderCountDRO.setMonthOrderCount(orderCount);

        return ResponseUtil.responseSuccessData(orderCountDRO);
    }

    @Override
    public ResponseDTO<OrderCountDRO> getOrderCountByShowProductId(Integer showProductId, Date month) {
        if (showProductId == null) {
            return ResponseUtil.responseFail("提交参数错误：前台产品id不能为空。");
        }
        if (month == null) {
            // 如果没提供月份，默认查当月
            month = DateUtil.getNow();
        }
        String monthFirstDay = DateUtil.getMonthFirstDay(month);
        String monthLastDay = DateUtil.getMonthLastDay(month);

        OrderWorkQuery query = new OrderWorkQuery();
        query.setShowProductId(showProductId);
        query.setReceiveTime(monthFirstDay + "," + monthLastDay);
        // 只查微信渠道
        query.setChannelIdList(Lists.newArrayList(GlobalConsts.CHANNEL_WEIXIN_ID));
        Integer orderCount = orderWorkListBService.countOrderWorkByQuery(query);
        logger.debug("[{}]前端产品查询销量数据[{}]", query, orderCount);
        OrderCountDRO orderCountDRO = new OrderCountDRO();
        orderCountDRO.setMonthOrderCount(orderCount);

        return ResponseUtil.responseSuccessData(orderCountDRO);
    }

    @Override
    public ResponseDTO<OrderCountDRO> getOrderCountByShowProductIdAndShopId(Integer productId, Date month, Integer shopId) {
        logger.debug("getOrderCountByShowProductIdAndShopId 收到请求 shopId[{}]", shopId);
        if (productId == null) {
            return ResponseUtil.responseFail("提交参数错误：产品id不能为空。");
        }

        ShopDIO shopDIO = new ShopDIO();
        shopDIO.setShopId(shopId);
        ResponseDTO<ShopDRO> shopResponse = shopRemoteService.getShop(shopDIO);
        logger.debug("getShop 获取店铺信息出参[{}]", shopResponse);
        if (!shopResponse.getStatusBool()) {
            return ResponseUtil.responseFail("店铺获取失败，未查询到对应的店铺id[" + shopId + "]的相关信息");
        }
        ShopDRO shopDRO = shopResponse.getData();

        OrderWorkQuery query = new OrderWorkQuery();
        if (!Objects.isNull(month)) {
            // 如果没提供月份，默认查当月
            String monthFirstDay = DateUtil.getMonthFirstDay(month);
            String monthLastDay = DateUtil.getMonthLastDay(month);
            query.setReceiveTime(monthFirstDay + "," + monthLastDay);
        }

        query.setShowProductId(productId);

        /* // 1 服务商店铺 2 渠道店铺
       if (Objects.equals(shopDRO.getType(), 1)) {
            query.setShopId(shopDRO.getShopId());
        }  else if (Objects.equals(shopDRO.getType(), 2)) {
            query.setChannelIdList(Lists.newArrayList(shopDRO.getChannelId()));
        }*/
        query.setPlat(Integer.valueOf(shopDRO.getPlat()));

        Integer orderCount = orderWorkListBService.countOrderWorkByQuery(query);
        logger.debug("[{}]后端产品查询销量数据[{}]", query, orderCount);
        OrderCountDRO orderCountDRO = new OrderCountDRO();
        orderCountDRO.setMonthOrderCount(orderCount);

        return ResponseUtil.responseSuccessData(orderCountDRO);
    }

    @Override
    public ResponseDTO<OrderCountShopDRO> getOrderCountByShowProductIdAndShopId(OrderCountShopDIO orderCountShopDIO) {
        logger.debug("getOrderCountByShowProductIdAndShopId 收到请求 orderCountShopDIO[{}]", orderCountShopDIO);
        ValidateResult validateResult = ValidatorUtil.validator(orderCountShopDIO);
        if (!validateResult.isSuccess()) {
            logger.error("[{}] 参数错误：{}", TAG, validateResult.toString());
            return ResponseUtil.responseFail("提交参数错误：" + validateResult.toString());
        }

        ShopDIO shopDIO = new ShopDIO();
        shopDIO.setShopId(orderCountShopDIO.getShopId());
        ResponseDTO<ShopDRO> shopResponse = shopRemoteService.getShop(shopDIO);

        if (!shopResponse.getStatusBool()) {
            return ResponseUtil.responseFail(shopResponse.getMessage());
        }
        ShopDRO shopDRO = shopResponse.getData();

        OrderWorkQuery query = new OrderWorkQuery();

        if (!Objects.isNull(orderCountShopDIO.getMonth())) {
            // 如果没提供月份，默认查当月
            String monthFirstDay = DateUtil.getMonthFirstDay(orderCountShopDIO.getMonth());
            String monthLastDay = DateUtil.getMonthLastDay(orderCountShopDIO.getMonth());
            query.setReceiveTime(monthFirstDay + "," + monthLastDay);
        }

/*        // 1 服务商店铺 2 渠道店铺
        if (Objects.equals(shopDRO.getType(), 1)) {
            query.setShopId(shopDRO.getShopId());
        }  else if (Objects.equals(shopDRO.getType(), 2)) {
            query.setChannelIdList(Lists.newArrayList(shopDRO.getChannelId()));
        }*/
        query.setPlat(Integer.valueOf(shopDRO.getPlat()));

        List<OrderCountShopDRO> orderCountShopDROList = Lists.newArrayList();

        orderCountShopDIO.getProductIdList().forEach(productId -> {
            query.setShowProductId(productId);
            Integer orderCount = orderWorkListBService.countOrderWorkByQuery(query);
            logger.debug("[{}]后端产品查询销量数据[{}]", query, orderCount);
            OrderCountShopDRO orderCountDRO = new OrderCountShopDRO();
            orderCountDRO.setProductId(productId);
            orderCountDRO.setMonthOrderCount(orderCount);
            orderCountShopDROList.add(orderCountDRO);
        });

        return ResponseUtil.responseSuccessItems(orderCountShopDROList);
    }

    private WeixinOrderDetailDRO getWeixinOrderDetailDRO(OrderWork orderWork) {
        Long orderId = orderWork.getOrderId();

        List<OrderProduct> orderProductList = orderProductService.listOrderProductByOrderIdSrcMaster(orderId);
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKeySrcMaster(orderId);

        WeixinOrderDetailDRO weixinOrderDetail = new WeixinOrderDetailDRO();
        weixinOrderDetail.setOrderId(orderId);
        int orderStatus = OrderStatusConsts.getOrderStatus(orderWork.getStatus(), orderWork.getResultStatus());
        weixinOrderDetail.setStatus(orderStatus);
        weixinOrderDetail.setStatusName(OrderStatusConsts.getOrderStatusName(orderStatus));
        weixinOrderDetail.setDutyTime(orderWork.getDutyTime());
        weixinOrderDetail.setCompleteTime(orderWork.getCompleteTime());
        weixinOrderDetail.setOriginalAmount(orderWork.getOriginalAmount());
        weixinOrderDetail.setTotalAmount(this.getTotalAmount(orderWork));
        weixinOrderDetail.setFactAmount(this.factAmount(orderWork));
        weixinOrderDetail.setPrepayAmount(orderWork.getPrepayAmount());
        weixinOrderDetail.setDiscountAmount(orderWork.getDiscountAmount());
        weixinOrderDetail.setMasterName(orderWork.getMasterName());
        weixinOrderDetail.setUserId(orderWork.getUserId());
        weixinOrderDetail.setUserName(orderDetail.getUserName());
        weixinOrderDetail.setWorkId(orderWork.getWorkId());
        weixinOrderDetail.setChannelId(orderWork.getChannelId());
        weixinOrderDetail.setCityId(orderWork.getCityId());
        weixinOrderDetail.setStreet(orderDetail.getStreet());
        weixinOrderDetail.setAddress(orderDetail.getAddress());
        weixinOrderDetail.setUserPhone(orderDetail.getTelephone());
        weixinOrderDetail.setServCategId(orderWork.getServCategId());
        weixinOrderDetail.setLatitude(orderDetail.getLatitude());
        weixinOrderDetail.setLongitude(orderDetail.getLongitude());
        weixinOrderDetail.setPrepayStatus(orderWork.getPrepayStatus());
        weixinOrderDetail.setFinalPrice(orderWork.getFinalPrice());
        weixinOrderDetail.setReceiveTime(orderWork.getReceiveTime());
        weixinOrderDetail.setRefundStatus(OrderConsts.getUserRefundStatus(NumberUtil.isNotNullOrZero(orderWork.getRefundTargetWorkId()), orderWork.getRefundReviewStatus(), orderWork.getPayStatus()));
        weixinOrderDetail.setServItemType(orderWork.getServItemType());
        // 产品信息
        List<OrderProductDRO> orderProductDROList = BeanMapper.mapList(orderProductList, OrderProductDRO.class);
        weixinOrderDetail.setOrderProductList(orderProductDROList);

        // 服务项信息
        try {
            List<ZsServiceItemVO> serviceItemVos = zsNormalOrderServiceItemBService.findServiceItemVo(orderId, orderWork.getWorkId());
            if (!CollectionUtils.isEmpty(serviceItemVos)) {
                List<OrderServiceItem> orderServiceItems = new LinkedList<>();
                for (ZsServiceItemVO obj : serviceItemVos) {
                    if (!CollectionUtils.isEmpty(obj.getServiceItemList())) {
                        orderServiceItems.addAll(obj.getServiceItemList());
                    }
                }
                List<OrderServiceItemDRO> orerServiceItemDRO = BeanMapper.mapList(orderServiceItems, OrderServiceItemDRO.class);
                weixinOrderDetail.setOrderServiceItemList(orerServiceItemDRO);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        // 评价信息
        OrderComment orderComment = orderCommentService.findCommentByKey(orderId);
        if (orderComment != null) {
            List<OrderCommentDetail> orderCommentDetailList = orderComment.getDetailList();
            OrderCommentDRO comment = new OrderCommentDRO();
            comment.setScore(orderComment.getScore());
            comment.setAppendContent(orderComment.getAppendContent());
            comment.setContent(orderComment.getContent());
            comment.setTypeName(OrderConsts.getCommentTypeName(orderComment.getType()));
            comment.setCommentTime(orderComment.getCreateTime());
            comment.setReplyContent(orderComment.getReplyContent());
            if (orderCommentDetailList != null) {
                List<String> commentDetailList = Lists.newArrayList();
                orderCommentDetailList.forEach(e -> commentDetailList.add(e.getMapName()));
                comment.setCommentDetailList(commentDetailList);
            }
            weixinOrderDetail.setComment(comment);
        }

        // 订单优惠明细
        List<OrderDiscount> discountList = zsOrderDiscountBService.listByOrderId(orderId);
        List<OrderDetailDiscountDRO> orderDetailDiscountList = BeanMapper.mapList(discountList, OrderDetailDiscountDRO.class);
        orderDetailDiscountList.forEach(e -> e.setCategName(DiscountTypeEnums.getSubName(e.getCateg())));
        weixinOrderDetail.setOrderDiscountList(orderDetailDiscountList);
        logger.debug("工单详情[{}]", weixinOrderDetail);
        return weixinOrderDetail;
    }

    /**
     * 获取实付金额
     * @param orderWork
     * @return
     */
    private Integer factAmountFromEsOrder(EsOrderWork orderWork) {
        Integer factAmount = null;
        if (Objects.equals(orderWork.getChannelPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getChannelPrepayAmount())) {
            factAmount = Optional.ofNullable(factAmount).orElse(0) + orderWork.getChannelPrepayAmount();
        }
        if (Objects.equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getPrepayAmount())) {
            factAmount = Optional.ofNullable(factAmount).orElse(0) + orderWork.getPrepayAmount();
        }
        if (Objects.equals(orderWork.getDepositStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getDepositAmount())) {
            factAmount = Optional.ofNullable(factAmount).orElse(0) + orderWork.getDepositAmount();
        }
        // TODO lujia 支付状态支付成功 代表尾款已经支付
        if (Objects.equals(orderWork.getPayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getMasterAmount())) {
            factAmount = Optional.ofNullable(factAmount).orElse(0) + orderWork.getMasterAmount();
        }
        return factAmount;
    }

    /**
     * 获取实付金额
     * @param orderWork
     * @return
     */
    private Integer factAmount(OrderWork orderWork) {
        Integer factAmount = null;
        if (Objects.equals(orderWork.getChannelPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getChannelPrepayAmount())) {
            factAmount = Optional.ofNullable(factAmount).orElse(0) + orderWork.getChannelPrepayAmount();
        }
        if (Objects.equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getPrepayAmount())) {
            factAmount = Optional.ofNullable(factAmount).orElse(0) + orderWork.getPrepayAmount();
        }
        if (Objects.equals(orderWork.getDepositStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getDepositAmount())) {
            factAmount = Optional.ofNullable(factAmount).orElse(0) + orderWork.getDepositAmount();
        }
        if (Objects.equals(orderWork.getMasterPayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil.isNullOrZero(orderWork.getMasterAmount())) {
            factAmount = Optional.ofNullable(factAmount).orElse(0) + orderWork.getMasterAmount();
        }
        return factAmount;
    }

    /**
     * 获取实付金额
     * @param orderWork
     * @return
     */
    private Integer getTotalAmount(OrderWork orderWork) {
        return orderWork.getTotalAmount();
/*        if (!Objects.equals(orderWork.getPayStatus(), GlobalConsts.REFUND_STATUS_DONE) && orderWork.getTotalAmount() != null) {
            return orderWork.getTotalAmount();
        }
        return this.factAmount(orderWork);*/
    }
}
